// pages/homePage/homePage.js
var app = getApp();
var provinces = []; //省s
var provinceNames = []; //省名称
var citys = []; //城市s
var cityNames = []; //城市名称
var countys = []; //区县s
var countyNames = []; //区县名称
var province = "" + 101101; //省
var city = "" + 101101101; //城市
var county = "" + 101101101101; //区县
Page({
  /**
   * 页面的初始数据
   */
  data: {
    username:'',
    telephone:'',
    wholeAddress:'',
    indicatorDots: true,
    autoplay: true,
    interval: 2000,
    duration: 1000,
    productType:[],
    multiArray: [],
    multiIndex: [0, 0, 0],
    addresss:'',
    index:-1,
  }, 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // 未授权，跳转到授权页面
    console.log("----"+wx.getStorageSync("telephone"))
    if(!wx.getStorageSync("userId")||!wx.getStorageSync("telephone")){
      console.info("未授权2");
      wx.reLaunch({
        url: '/pages/myPage/myPage',
      })
    }







    const pages = getCurrentPages()
    const currPage = pages[pages.length - 1]
    // this.getUserLocation();
    // this.getProvinceData();
    //获取手机高度
    this.setData({
      navH: app.globalData.navHeight
    })
    wx.request({
      url: app.globalData.url + 'getProductUserLikeList',
      data: {
        userId: wx.getStorageSync("userId"),
      },
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        for (var i = 0; i < res.data.data.length; i++) {
          if (res.data.data[i].promotionMsg !=undefined) {
            var arr = res.data.data[i].promotionMsg.split(",");
            res.data.data[i].arr = arr;
          } else {
            res.data.data[i].arr = [];
          }
          if (res.data.data[i].promotionType != undefined) {
            //先按照逗号分割字符串
            let arrycode = res.data.data[i].promotionType.split(",");
            //去重
            arrycode = Array.from(new Set(arrycode));
            //拼接正确的nextOperatorCode
            res.data.data[i].promotionType = arrycode = arrycode.toLocaleString();
            // var promotionType = res.data.data[i].promotionType.split(",");
            // res.data.data[i].promotionType = promotionType;
          } else {
            res.data.data[i].promotionType = [];
          }
        }
        
        that.setData({
          likeList: res.data.data
        })
      }
    })

    wx.request({
      url: app.globalData.url + "getUserAddressList",
      method: "GET",
      data: {
        userId: wx.getStorageSync("userId")
      },
      success: function (res) {
        var data = res.data.data;
        if (res.data.result == 1) {
          if (data.length > 0) {
            console.log(currPage.data.wholeAddress)
            if (currPage.data.wholeAddress == "" && that.data.index == -1) {
              that.setData({
                data: data.length,
                username: data[0].username,
                telephone: data[0].telephone,
                provinceName: data[0].provinceName,
                cityName: data[0].cityName,
                districtName: data[0].districtName,
                streetName: data[0].streetName,
                wholeAddress: data[0].wholeAddress,
                addrId: data[0].addrId,
              })
              console.info("adad1" +data[0].addrId);
            } else if (that.data.index != -1) {
              console.info(data);
              that.setData({
                data: data.length,
                username: data[that.data.index].username,
                telephone: data[that.data.index].telephone,
                provinceName: data[that.data.index].provinceName,
                cityName: data[that.data.index].cityName,
                districtName: data[that.data.index].districtName,
                streetName: data[that.data.index].streetName,
                wholeAddress: data[that.data.index].wholeAddress,
                addrId: data[that.data.index].addrId,
              })
              console.info("adad===" + currPage.data.addrId);

            } else {

              console.info("adad===" + currPage.data.addrId);

            }

          } else {
            that.setData({
              data: 0
            })
          }

        }
      }
    });

    //首页文字弹窗
    wx.request({
      url: app.globalData.url + "getFistPageAdvice",
      method: "GET",
      data: {
      },
      success: function (res) {
        var data = res.data.data;
        if (data&&data.msg) {
          wx.showModal({
            title: '温馨提示',
            confirmText:'我已知晓',
            showCancel:false,
            content: data.msg,
            success (res) {
              
            }
          })
        }
      }
    })
  },
  
  //选择地址
  bindaddress: function () {
    wx.navigateTo({
      url: '/pages/addressList/addressList?userId='+wx.getStorageSync("userId")
      })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var that = this;
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    that.setData({
      token: wx.getStorageSync("token")
    });
    const pages = getCurrentPages()
    const currPage = pages[pages.length - 1]  // 当前页
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  
  // 获取省份数据
  getProvinceData: function () {
    var that = this;
    var s;
    wx.request({
      url: app.globalData.url + 'getAddressLib', //
      data: {
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var arr = res.data.data;
        // 更新数据  
        for (var i = 0; i < arr.length; i++) {
          provinceNames[i] = arr[i].province;
          provinces[i] = arr[i].code;
        }

        that.setData({
          provinces: provinces,
          provinceNames: provinceNames

        })
        that.getCityArr(provinces[0]);
      },
      fail: function (err) {

      },
    })
  },

  // 获取城市数据
  getCityArr: function (arr, count = 0) {
    var that = this;
    var c;
    wx.request({
      url: app.globalData.url + 'getAddressCityLib', //
      data: {
        parent: arr
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var arr = res.data.data;
        for (var i = 0; i < arr.length; i++) {
          cityNames[i] = arr[i].city;
          citys[i] = arr[i].code;
        }
        // 更新数据  
        that.setData({
          citys: citys,
          cityNames: cityNames
        })
        city = citys[0];
        that.getCountyInfo(city, 0);
      },
      fail: function (err) {

      },
    })
    if (citys.length == 0) {
      citys[0] = {
        name: ''
      };
      cityNames[0] = {
        name: ''
      };
    }

  },

  // 获取区县数据
  getCountyInfo: function (arr, column = 0) {
    var that = this;
    var c;
    countys = [];
    countyNames = [];
    wx.request({
      url: app.globalData.url + 'getAddressCountyLib', //
      data: {
        parent: arr
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var arr = res.data.data;
        for (var i = 0; i < arr.length; i++) {
          countyNames[i] = arr[i].district;
          countys[i] = arr[i].code;
        }
        county = countys[0];
        // 更新数据  
        that.setData({
          countys: countys,
          countyNames: countyNames,
          // value: value,
        })
        that.getMultiArray();
      },
      fail: function (err) {

      },
    })
    if (countys.length == 0) {
      countys[0] = {
        name: ''
      };
      countyNames[0] = {
        name: ''
      };
    };

    that.setData({
      countys: countys,
      countyNames: countyNames,
    })
  },



  bindMultiPickerColumnChange: function (e) {
    var that = this;
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    if (e.detail.column == 0) {
      that.data.multiIndex = [e.detail.value, 0, 0];
    } else if (e.detail.column == 1) {
      //如果更新的是第二列“市”，第一列“省”的下标不变，第三列“区”的数组下标置为0
      that.data.multiIndex = [that.data.multiIndex[0], e.detail.value, 0];
    } else if (e.detail.column == 2) {
      //如果更新的是第三列“区”，第一列“省”和第二列“市”的值均不变。
      that.data.multiIndex = [that.data.multiIndex[0], that.data.multiIndex[1], e.detail.value];
    }
    if (e.detail.column == 0) {
      var val = e.detail.value;
      var arr = that.data.provinces[val];
      that.getCityArr(arr, val); //获取地级市数据
      this.setData({
        multiIndex: that.data.multiIndex,
      })
    } else if (e.detail.column == 1) {
      var val = e.detail.value;
      var arr = that.data.citys[val];
      that.getCountyInfo(arr, val); //获取区县数据
      this.setData({
        multiIndex: that.data.multiIndex,
      })
    }else if (e.detail.column == 2) {
      this.setData({
        multiIndex: that.data.multiIndex,
      })
    }
  },
  getMultiArray: function () {
    var that = this;
    console.log(that.data.countyNames.length);
    var multiArray = '[';
    for (var i = 0; i < that.data.provinceNames.length; i++) {
      multiArray += '{"city":[';
      for (var j = 0; j < that.data.cityNames.length; j++) {
        multiArray += '{"areas":[';
        for (var k = 0; k < that.data.countyNames.length; k++) {
          multiArray += '{"code":"' + that.data.countys[k] + '","name":"' + that.data.countyNames[k] + '"},';
        }
        multiArray = multiArray.substring(0, multiArray.length - 1);
        multiArray += '],"code":"' + that.data.citys[j] + '","name":"' + that.data.cityNames[j] + '"},';
      }
      multiArray = multiArray.substring(0, multiArray.length - 1);
      multiArray += '],"code":"' + that.data.provinces[i] + '","name":"' + that.data.provinceNames[i] + '"},';
    }
    multiArray = multiArray.substring(0, multiArray.length - 1);
    multiArray += ']';
    var multiArray1 = JSON.parse(multiArray);
    console.log(multiArray1);
    that.setData({
      multiArray: [multiArray1, multiArray1[0].city, multiArray1[0].city[0].areas]
    })
    
  },
  navBack: function () {
    wx.navigateBack({
    })
  },
  extract:function(){
    var that = this;
    // if (that.data.cardNo==undefined) {
    //   wx.showToast({
    //     title: "请输入卡号",
    //     icon: 'none'
    //   })
    //   return;
    // }
    // if (that.data.pickUpGoodCode == undefined) {
    //   wx.showToast({
    //     title: "请输入提货码",
    //     icon: 'none'
    //   })
    //   return;
    // }
    // if (that.data.username == undefined) {
    //   wx.showToast({
    //     title: "请输入收货人姓名",
    //     icon: 'none'
    //   })
    //   return;
    // }
    // if (that.data.telephone == undefined) {
    //   wx.showToast({
    //     title: "请输入联系方式",
    //     icon: 'none'
    //   })
    //   return;
    // }
    // if (that.data.addresss == undefined) {
    //   wx.showToast({
    //     title: "请输入收货地址",
    //     icon: 'none'
    //   })
    //   return;
    // } 
    // wx.showModal({
    //   title: '提示',
    //   content: '确定要提货吗？',
    //   success: function (sm) {
    //     if (sm.confirm) {
    //       // 用户点击了确定 可以调用取消订单的方法了
    //       wx.request({
    //         url: app.globalData.url + 'submitOrder', //
    //         data: {
    //           type: 7,
    //           cardNo: that.data.cardNo,//卡号
    //           pickUpGoodCode: that.data.pickUpGoodCode,//提货码
    //           address: that.data.wholeAddress,
    //           telephone: that.data.telephone,
    //           username: that.data.username,
    //           userId: wx.getStorageSync("userId"),
    //           payChannel: 5005,
    //         },
    //         method: 'POST',
    //         header: {
    //           'content-type': 'application/x-www-form-urlencoded'
    //         },
    //         success: function (res) {
    //           if (res.data.result == 1) {
    //            wx.navigateTo({
    //              url: '',
    //            })
    //           }else{
    //             wx.showToast({
    //               title: res.data.errmsg,
    //               icon: 'none'
    //             })
    //           }
    //         },
    //         fail: function (err) {

    //         },
    //       })
    //     }
    //   }
    // });
    wx.request({
      url: app.globalData.url + 'getGiftCardProductIdByCardNo', //
      data: {
        cardNo: that.data.cardNo,//卡号
        pickUpGoodCode: that.data.pickUpGoodCode,//提货码
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.result == 1) {
          wx.navigateTo({
            url: '/pages/giftCardDetails/giftCardDetails?productid=' + res.data.data.productId+"&cardNo="+that.data.cardNo+"&pickUpGoodCode="+that.data.pickUpGoodCode+"&address="+that.data.wholeAddress+"&telephone="+that.data.telephone+"&username="+that.data.username,
          })
        }else{
          wx.showToast({
            title: res.data.errmsg,
            icon: 'none'
          })
        }
      },
      fail: function (err) {

      },
    })

  },
  cardNo:function(e){
    var that = this; 
    that.setData({
      cardNo: e.detail.value
    })
  },
  pickUpGoodCode: function (e) {
    var that = this;
    that.setData({
      pickUpGoodCode: e.detail.value
    })
  },
  telephone: function (e) {
    var that = this;
    that.setData({
      telephone: e.detail.value
    })
  },
  username: function (e) {
    var that = this;
    that.setData({
      username: e.detail.value
    })
  },
  addresss: function (e) {
    var that = this;
    
    that.setData({
      addresss:e.detail.value
    })
  },
  immeBuy:function(){
    var that = this;
    var that = this;
    
  },
   /**
   * 跳转到产品详情
   */
  details: function(res) {
    var productid = res.currentTarget.dataset.productid;
    var type = res.currentTarget.dataset.type;
    wx.navigateTo({
      url: '/pages/productDetail/productDetail?productid=' + productid + '&type=' + type,
    })
   
  },
})